"""Q&A API Router"""
from typing_extensions import Annotated

from fastapi import (
    APIRouter, BackgroundTasks, Depends, HTTPException, Request
)
from fastapi.responses import FileResponse

from core.models import Member, QaContent
from lib.common import get_paging_info
from lib.mail import send_qa_mail
from api.v1.dependencies.member import get_current_member
from api.v1.dependencies.qa import get_qa_content, get_qa_file, get_upload_file_data, validate_data
from api.v1.service.qa import QaConfigServiceAPI, QaFileServiceAPI, QaServiceAPI
from api.v1.models.response import (
    MessageResponse, response_401, response_403, response_404, response_422, response_500
)
from api.v1.models.qa import (
    QaConfigResponse, QaContentData, QaContentListResponse, QaContentList, QaContentResponse
)

router = APIRouter()


@router.get("/qa/config",
            summary="Q&A 设置查询",
            responses={**response_500})
async def read_qa_config(
    service: Annotated[QaConfigServiceAPI, Depends()]
) -> QaConfigResponse:
#    “在Q&A页面上查看所需的设置。”
    return service.qa_config


@router.get("/qas",
            summary="Q&A 列表查询",
            responses={**response_401, **response_403, **response_422})
async def read_qa_contents(
    service: Annotated[QaServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member)],
    search: Annotated[QaContentList, Depends()]
) -> QaContentListResponse:
    # “查看认证会员的Q&A列表。”
    total_records = service.fetch_total_records(member, **search.__dict__)
    paging_info = get_paging_info(search.page, search.per_page, total_records)
    qa_contents = service.read_qa_contents(member, search.offset,
                                           search.per_page, **search.__dict__)
    return {
        "total_records": total_records,
        "total_pages": paging_info["total_pages"],
        "qa_contents": qa_contents
    }


@router.get("/qas/{qa_id}",
            summary="Q&A 详细询价",
            responses={**response_401, **response_403,
                       **response_404, **response_422})
async def read_qa(
    service: Annotated[QaServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member)],
    qa_content: Annotated[QaContent, Depends(get_qa_content)],
    search: Annotated[QaContentList, Depends()]
) -> QaContentResponse:
    """认证会员 Q&A 1我抬头看枪。."""
    qa_id = qa_content.qa_id
    answer = service.read_qa_answer(qa_id)
    prev_qa, next_qa = service.fetch_prev_next_qa(member, qa_id, **search.__dict__)
    related_qa_contents = service.fetch_related_qa_contents(member, qa_id)

    return {
        "qa_content": qa_content,
        "answer": answer,
        "prev": prev_qa,
        "next": next_qa,
        "related": related_qa_contents,
    }


@router.post("/qas",
             name="create_qa_content",
             summary="Q&A 注册",
             responses={**response_401, **response_403, **response_422})
async def create_qa_content(
    request: Request,
    background_tasks: BackgroundTasks,
    member: Annotated[Member, Depends(get_current_member)],
    service: Annotated[QaServiceAPI, Depends()],
    data: Annotated[QaContentData, Depends(validate_data)],
) -> MessageResponse:
    """
        注册Q&A。
        -注册问题时，向管理员发送邮件
        -注册回复时，向用户发送邮件

        ### Request Body
        -**qa_subject**：标题
        -**qa_content**：内容
        -**qa_related**：相关Q&A ID
        -**qa_email**：电子邮件地址
        -**qa_hp**：手机号码
        -**qa_email_recv**：是否收到电子邮件
        -**qa_sms_recv**：是否收到短信
        -**qa_html**：是否使用HTML
        -**qa_1**：额外字段1
        -**qa_2**：额外字段2
        -**qa_3**：额外字段3
        -**qa_4**：额外字段4
        -**qa_5**：额外字段5

    """
    qa_content = service.create_qa_content(member, data)

    #Q&A注册的通知邮件发送处理（后台）
    background_tasks.add_task(send_qa_mail, request, qa_content)

#TODO:如果启用SMS通知选项，则需要添加SMS发送功能
# if qa_config.qa_use_sms:
#     pass

    return {
        "message": "Q&A注册已完成。",
    }


@router.put("/qas/{qa_id}",
            summary="Q&A 校正",
            responses={**response_401, **response_403,
                       **response_404, **response_422})
async def update_qa_content(
    service: Annotated[QaServiceAPI, Depends()],
    qa_content: Annotated[QaContent, Depends(get_qa_content)],
    data: Annotated[QaContentData, Depends(validate_data)],
) -> MessageResponse:
# """
# 修改Q&A。

# ### Request Body
# -**qa_subject**：标题
# -**qa_content**：内容
# -**qa_related**：相关Q&A ID
# -**qa_email**：电子邮件地址
# -**qa_hp**：手机号码
# -**qa_email_recv**：是否收到电子邮件
# -**qa_sms_recv**：是否收到短信
# -**qa_html**：是否使用HTML
# -**qa_1**：额外字段1
# -**qa_2**：额外字段2
# -**qa_3**：额外字段3
# -**qa_4**：额外字段4
# -**qa_5**：额外字段5
# """
    service.update_qa_content(qa_content, data)

    return {
        "message": "Q&A 更正已完成.",
    }


@router.put("/qas/{qa_id}/files",
            summary="Q&A 文件上传",
            responses={**response_401, **response_403,
                       **response_404, **response_422})
async def upload_qa_file(
    service: Annotated[QaFileServiceAPI, Depends()],
    qa_content: Annotated[QaContent, Depends(get_qa_content)],
    data: Annotated[dict, Depends(get_upload_file_data)],
) -> MessageResponse:
# """
# 将文件上载到Q&A。

# ### Request Body
# -**file1**：附件1
# -**file2***:附件2
# -**file_del1**：是否删除附件1
# -**file_del2**：是否删除附件2
# """
    service.upload_qa_file(qa_content, data)

    return {
        "message": "Q&A 文件上传完成.",
    }


@router.get("/qas/{qa_id}/files/{file_index}",
            summary="Q&A 下载文件",
            responses={**response_401, **response_403, **response_404})
async def download_qa_file_from_api(
    qa_file: Annotated[dict, Depends(get_qa_file)]
) -> FileResponse:
    """Q&A将文件下载到."""
    try:
        return FileResponse(qa_file["path"], filename=qa_file["name"])
    except Exception as e:
        raise HTTPException(400, f"文件下载失败. {e}") from e


@router.delete("/qas/{qa_id}",
               summary="Q&A 删除",
               responses={**response_401, **response_403, **response_404})
async def delete_qa_content(
    service: Annotated[QaServiceAPI, Depends()],
    qa_content: Annotated[QaContent, Depends(get_qa_content)],
) -> MessageResponse:
    """Q&A要删除."""
    service.delete_qa_content(qa_content)

    return {
        "message": "Q&A 删除完成.",
    }
